package cn.ztydata.teachingsystem.heaven.dao.redis;

import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.stereotype.Repository;

import java.util.Set;

/**
 * 课程->知识点 redis类
 * Created by chenxin on 2014/12/8.
 */
@Repository
public class CourseKpDao extends BaseRedisDao {
    /**
     * 保存课程与知识点的关系
     * @param courseId 课程ID
     * @param kpId 知识点ID
     * @return Short
     *
     * @author cx
     * @since 214-12-08
     */
    public Boolean saveKp(final long courseId, final long kpId) {
        SessionCallback<Boolean> sessionCallback = new SessionCallback<Boolean>() {
            @Override
            public Boolean execute(RedisOperations operations) throws DataAccessException {
                operations.multi();
                //获取Set操作
                SetOperations<String, Long> setOperations = operations.opsForSet();

                //保存课程->知识点的关系
                setOperations.add(KeyUtils.courseKp(courseId), kpId);
                //保存知识点->课程的关系
                setOperations.add(KeyUtils.kpCourse(kpId), courseId);

                operations.exec();
                return true;
            }
        };

        logger.debug("保存课程与知识点的关系");
        return (Boolean)redisTemplate.execute(sessionCallback);
    }

    /**
     * 删除课程与知识点的关系
     * @param kpId 知识点ID
     * @param courseId 课程ID
     * @return Boolean
     *
     * @author cx
     * @since 2014-12-09
     */
    public Boolean deleteKp(final long kpId, final long courseId) {
        SessionCallback<Boolean> sessionCallback = new SessionCallback<Boolean>() {
            @Override
            public Boolean execute(RedisOperations operations) throws DataAccessException {
                operations.multi();
                //获取Set操作
                SetOperations<String, Long> setOperations = operations.opsForSet();

                //删除课程->知识点的关系
                setOperations.remove(KeyUtils.courseKp(courseId), kpId);
                //删除知识点->课程的关系
                setOperations.remove(KeyUtils.kpCourse(kpId), courseId);

                operations.exec();
                return true;
            }
        };

        logger.debug("删除课程与知识点的关系");
        return (Boolean)redisTemplate.execute(sessionCallback);
    }

    /**
     * 获取课程的知识点ID集合
     * @param courseId 课程ID
     * @return Set
     *
     * @author cx
     * @since 2014-12-09
     */
    public Set<Long> getKpIds(final long courseId) {
        //获取Set操作
        SetOperations<String, Long> setOperations = redisTemplate.opsForSet();
        logger.debug("获取课程的知识点ID集合");
        return setOperations.members(KeyUtils.courseKp(courseId));
    }
}
